<?php
    class WZ_Service
    {
        static $model;
        static $object;
        static $row;
        static $db;
        static $_instance = array();
        
        public static function run($obj)
        {
            $class = get_class($obj);
            static::$model = str_replace('WZService_', 'WZModel_', $class);
            if (!array_key_exists(static::$model, static::$_instance)) {
				static::$_instance[static::$model] = new self;
			}
            $self = get_class(static::$_instance[static::$model]);
            if ($class != $self) {                
                static::$db = \Loader::WZ_Activerecord(new static::$model);
            }
            return static::$_instance;
        }
        
        public static function find($id)
        {
            return static::$db->find($id);
        }
        
        public static function findBy($column, $value, $one = false)
        {
            return static::$db->findBy($column, $value, $one);
        }
        
        public static function getDb()
        {
            return static::$db;
        }
        
        public static function __callStatic($name, $args)
        {
            if (strncmp($name, 'findBy', 6) === 0) {
                return static::findBy(substr($name, 6), reset($args));
            }
            elseif (strncmp($name, 'findOneBy', 9) === 0) {
                return static::findBy(substr($name, 9), reset($args), true);
            }
            throw new \BadMethodCallException('Method "' . \WZ_Inflector::clean($name) . '" does not exist.');
        }
    }